package gen.tools.deploy;

import gen.tools.Widgets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.filter.HTTPDigestAuthFilter;

public class ChkAPdep extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public ChkAPdep() {
        super();
    } 

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		final Widgets wid = new Widgets();
		response.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/json");
		
		final Client client = Client.create();
		final String apURL = request.getParameter("apURL");
        final String apUSR = request.getParameter("apUSR");
        final String apPWD = request.getParameter("apPWD");
        final int apPORT = Integer.parseInt( request.getParameter("apPORT") );
		
	    client.addFilter(new HTTPDigestAuthFilter(apUSR, apPWD)); // must be in the ManagementRealm
	    final WebResource resource = client.resource("http://"+apURL+":"+(apPORT-9)+"/management?recursive");
	    final WebResource.Builder requestBuilder = resource.getRequestBuilder();
	    //final String tmp = new GsonBuilder().disableHtmlEscaping().create().toJson( requestBuilder.get(String.class) ).replaceAll("\"","'");
	    final String tmp = new Gson().toJson( requestBuilder.get(String.class) ); 
	    response.getWriter().write( tmp );
	    //new GsonBuilder().disableHtmlEscaping().create().toJson( requestBuilder.get(String.class) ).replaceAll("'", "\"")
	}

}
